<template>
    <el-form label-width="100px">
        <el-row>
            <!-- 在同一行的表单项 -->
            <el-col :span="12">
                <el-form-item label="文章标题">
                    <el-input v-model="formParams.articleTitle" placeholder="文章标题"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="标签">
                    <el-tag style="margin:0px 5px" v-for="tag in dynamicTags" :key="tag" closable
                        :disable-transitions="false" @close="handleClose(tag)">
                        {{ tag }}
                    </el-tag>
                    <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="w-20" size="small"
                        @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
                    <el-button v-else class="button-new-tag" size="small" @click="showInput">
                        + New Tag
                    </el-button>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="6">
                <el-form-item label="栏目名称">
                    <el-select v-model="formParams.column.columnId">
                        <el-option v-for="(item, index) in allColumn" :key="item.columnId" :label="item.columnTitle"
                            :value="item.columnId"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="排序" prop="seq">
                    <el-input v-model="formParams.seq" placeholder="1"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="6">
                <el-form-item label="是否免费" prop="charge">
                    <el-radio-group v-model="formParams.charge" class="ml-4">
                        <el-radio :label="1" size="large">收费</el-radio>
                        <el-radio :label="0" size="large">免费</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="是否显示" prop="display">
                    <el-radio-group v-model="formParams.display" class="ml-4">
                        <el-radio :label="1" size="large">显示</el-radio>
                        <el-radio :label="0" size="large">隐藏</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="布局" prop="recommend">
                    <el-radio-group v-model="formParams.layout" class="ml-4">
                        <el-radio :label="0" size="large">页面</el-radio>
                        <el-radio :label="1" size="large">音频</el-radio>
                        <el-radio :label="2" size="large">视频</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="12">
                <el-form-item label="封面图" prop="display">
                    <el-upload v-model:file-list="imgList" action="/api/v1/m/upload" list-type="picture-card"
                        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="handlerUpload">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" style="width:100%;height: 100%;" />
                    </el-dialog>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="摘要" prop="articleSummary">
                    <el-input type="textarea" :rows="6" v-model="formParams.articleSummary" placeholder="栏目摘要"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col>
                <el-form-item>
                    <el-tabs v-model="activeTab">
                        <el-tab-pane label="音频" name="audio">
                            <el-upload class="upload-demo" action="/api/v1/m/upload" :on-success="audioHandleUploadSuccess"
                                :before-upload="audioBeforeUpload" :file-list="audioFileList" :limit="1">
                                <el-button slot="trigger" size="small" type="primary">上传</el-button>
                                <div slot="tip" class="el-upload__tip">只能上传 mp3</div>
                            </el-upload>
                            <audio v-if="audioSrc" :src="audioSrc" controls>
                                Your browser does not support the audio tag.
                            </audio>
                        </el-tab-pane>
                        <el-tab-pane label="视频" name="video">
                            <el-upload class="upload-demo-video" action="/api/v1/m/upload"
                                :on-success="videoHandleUploadSuccess" :before-upload="videoBeforeUpload"
                                :file-list="videoFileList" :limit="1">
                                <el-button slot="trigger" size="small" type="primary">上传</el-button>
                                <div slot="tip" class="el-upload__tip">只能上传 mp4</div>
                            </el-upload>
                            <video ref="videoRef" class="video-player" v-if="videoSrc" controls>
                                <source :src="videoSrc" type="video/mp4">
                                抱歉，你的浏览器不支持内嵌视频，你可以 <a :href="videoSrc">下载</a> 并查看。
                            </video>
                        </el-tab-pane>
                    </el-tabs>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="24">
                <el-form-item label="栏目html" prop="articleContent">
                    <!-- <el-input type="textarea" :rows="6" v-model="formParams.columnIntro" placeholder="栏目htm"></el-input> -->
                    <WangEditor v-model="formParams.articleContent"></WangEditor>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="24">
                <el-form-item>
                    <el-button :disabled="formParams.articleTitle.length > 0 ? false : true" type="primary" size="default"
                        @click="save">保存</el-button>
                    <el-button type="primary" size="default" @click="cancel">取消</el-button>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
</template>

<script setup lang="ts">
import { ref, nextTick, reactive, watch } from 'vue'
import { ElInput } from 'element-plus'
import type { TArticle } from '@/api/content/article/type'
import { reqAddOrUpdateArticle } from '@/api/content/article'

import { reqColumnList } from '@/api/content/column'
import type { TColumn, TColumnListResponseData, } from '@/api/content/column/type'

import type { UploadProps, UploadUserFile } from 'element-plus'

import { ElMessage } from 'element-plus'
import { TMedia } from '@/api/content/media/type'

let $emit = defineEmits(['changeScene'])
//点击取消按钮:通知父组件切换场景为1,展示有的SPU的数据
const cancel = () => {
    $emit('changeScene', { flag: 0, params: 'update' })
}

const activeTab = ref('audio')
const audioSrc = ref<string>('');
const audioFileList = ref<{ name: string, url: string }[]>([]);
const videoSrc = ref<string>('');
const videoFileList = ref<{ name: string, url: string }[]>([]);


const inputValue = ref('')
const dynamicTags = ref<string[]>([])
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()


const handleClose = (tag: string) => {
    dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const videoRef = ref<HTMLVideoElement | null>(null);
// 观察 videoSrc.value 的变化， 当它变化时，重新加载视频
watch(videoSrc, () => {
    if (videoRef.value) {
        videoRef.value.load();
    }
}, { immediate: true });  // immediate: true 确保侦听器会在开始之后立即被调用一次

const audioBeforeUpload = (file: any) => {
    const isAudio = file.type === 'audio/mpeg';
    if (!isAudio) {
        ElMessage({
            type: "error",
            message: '应该为音频文件 mp3'
        })
    }
    return isAudio;
};

const videoBeforeUpload = (file: any) => {
    const isVideo = file.type === 'video/mp4';
    if (!isVideo) {
        ElMessage({
            type: "error",
            message: '应该为视频文件 mp4'
        });
    }
    return isVideo;
};

const audioHandleUploadSuccess = (response: any, file: any) => {
    audioSrc.value = response.data.url;
    audioFileList.value = [{ name: file.name, url: audioSrc.value }];
    formParams.value.media = response.data
}
const videoHandleUploadSuccess = (response: any, file: any) => {
    videoSrc.value = response.data.url;
    videoFileList.value = [{ name: file.name, url: videoSrc.value }];
    formParams.value.media = response.data
}

const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
        InputRef.value!.input!.focus()
    })
}

const handleInputConfirm = () => {
    if (inputValue.value) {
        dynamicTags.value.push(inputValue.value)
    }
    inputVisible.value = false
    inputValue.value = ''
}

let allColumn = ref<TColumn[]>([])

//商品图片
let imgList = ref<UploadUserFile[]>([
    {
        'url': '',
        name: ''
    },
])

//控制对话框的显示与隐藏
let dialogVisible = ref<boolean>(false)
//存储预览图片地址
let dialogImageUrl = ref<string>('')
//存储已有的SPU对象
const columnInitValue = {
    columnId: '',
    columnTitle: '',
    columnIntro: '',

    charge: 0,
    price: 0,
    reward: 0,
    display: 0,
    recommend: 0,
    columnSeq: 0,

    tag: '',
    summary: '',
    sets: 0,
    author: {
        nickName: '',
    },
    age: {

    },
    columnType: {
        typeId: 0
    },
}
let formParams = ref<TArticle>({
    articleId: '',
    articleTitle: '',
    articleSummary: '',
    articleContent: '',
    articleCover: '',
    display: 0,
    seq: 0,
    charge: 0,
    layout: 0,
    column: columnInitValue,
    media: {
        mediaId: '',
        url: '',
        mediaType: 0
    }
})

const resetForms = () => {
    // formParams.authorId = ''

}

const initallColumn = async () => {
    let result: TColumnListResponseData = await reqColumnList(1, 100, '')
    allColumn.value = result.data.list
}

const resetVariables = () => {
    imgList.value = [
        {
            'url': '',
            name: ''
        }
    ]
    audioFileList.value = [
        // {
        //     'url': '',
        //     name: ''
        // }
    ]
    videoFileList.value = [
        // {
        //     'url': '',
        //     name: ''
        // }
    ]
    audioSrc.value = ''
    videoSrc.value = ''
    dynamicTags.value = []
}
const initHasArticleData = async (column: TArticle) => {
    resetVariables()
    formParams.value = column
    if (!formParams.value.column) {
        formParams.value.column = columnInitValue
    }

    if (column && column.tag) {
        dynamicTags.value = column.tag.split(',');
    }

    if (formParams.value.media) {
        if (formParams.value.media.mediaType === 2) {
            audioSrc.value = formParams.value.media.url
        } else if (formParams.value.media.mediaType === 3) {
            videoSrc.value = formParams.value.media.url
        }
    }

    initallColumn()


    let url = formParams.value.articleCover;
    if (url !== undefined) {
        imgList.value[0].url = url;
        imgList.value[0].name = url.substring(url.lastIndexOf('/') + 1);
    }
}
//照片墙点击预览按钮的时候触发的钩子
const handlePictureCardPreview = (file: any) => {
    dialogImageUrl.value = file.url
    //对话框弹出来
    dialogVisible.value = true
}
//照片墙删除文件钩子
const handleRemove = () => {
    console.log(123)
}
//照片钱上传成功之前的钩子约束文件的大小与类型
const handlerUpload = (file: any) => {
    if (
        file.type == 'image/png' ||
        file.type == 'image/jpeg' ||
        file.type == 'image/gif'
    ) {
        if (file.size / 1024 / 1024 < 3) {
            return true
        } else {
            ElMessage({
                type: 'error',
                message: '上传文件务必小于3M',
            })
            return false
        }
    } else {
        ElMessage({
            type: 'error',
            message: '上传文件务必PNG|JPG|GIF',
        })
        return false
    }
}


//保存按钮的回调
const save = async () => {
    //1:照片墙的数据
    if (imgList.value[0] && typeof imgList.value[0].response === 'object' && imgList.value[0].response !== null) {
        const responseData = imgList.value[0].response as { data: { url: string } };
        if (responseData.data && responseData.data.url) {
            formParams.value.articleCover = responseData.data.url;
        } else {
            formParams.value.articleCover = imgList.value[0].url;
        }
    } else if (imgList.value[0] && imgList.value[0].url) {
        formParams.value.articleCover = imgList.value[0].url;
    }

    formParams.value.tag = dynamicTags.value.join(",")

    let result = await reqAddOrUpdateArticle(formParams.value)
    if (result.code == 0) {
        ElMessage({
            type: 'success',
            message: formParams.value.articleId ? '更新成功' : '添加成功',
        })
        //通知父组件切换场景为0
        $emit('changeScene', {
            flag: 0,
            params: formParams.value.articleId ? 'update' : 'add',
        })
    } else {
        ElMessage({
            type: 'success',
            message: formParams.value.articleId ? '更新成功' : '添加成功',
        })
    }
}

//初始化请求方法，父组件会引用
const initAddColumn = async () => {
    //清空数据
    Object.assign(formParams.value, {
        articleId: '',
        articleTitle: '',
        articleSummary: '',
        articleContent: '',
        articleCover: '',
        display: 0,
        seq: 0,
        charge: 0,
        layout: 0,
        column: columnInitValue,
    })
    resetVariables()

    //获取全部品牌的数据
    initallColumn()

}
//对外暴露
defineExpose({ initHasArticleData, initAddColumn })
</script>

<style scoped>
.video-player {
    width: 500px;
    height: 300px;
}

.audio-player {
    width: 500px;
}
</style>
